﻿using Mforj.Common.Utils;
using smforj.common.dao;
using smforj.common.model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;

namespace smforj.common.service
{
    /// <summary>
    /// 操作数据的Service
    /// </summary>
    public interface IWardRobeService : IUpload
    {
        /// <summary>
        /// 保存数据到本地
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        void SaveToLocalBatch(List<WardRobe> list);

        /// <summary>
        /// 保存展示数据到本地
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        void SaveShowToLocalBatch(List<WardRobe> list);


        /// <summary>
        /// 查询所有的喜好信息
        /// </summary>
        /// <returns></returns>
        List<PreferenceShow> GetPreferenceShows(IQuery query);
    }


    /// <summary>
    /// 衣柜数据操作Service
    /// </summary>
    public class WardRobeServiceImpl : IWardRobeService
    {
        /// <summary>
        /// 保存到本地
        /// </summary>
        private IWardRobeDao wardRobeDao = new WardRobeSqliteDaoImpl();
        private IFittingService fittingService = new FittingServiceImpl();
        private static HttpHelper httpHelper = new HttpHelper();
        private static JsonHelper jsonHelper = new JsonHelper(); 
        /// <summary>
        /// 操作数据的Service
        /// </summary>
        public void SaveToLocalBatch(List<model.WardRobe> list)
        {
            wardRobeDao.SaveWardRoleBatch(list);
        }

        /// <summary>
        /// 上传数据到远程服务器
        /// </summary>
        public int UploadData()
        {
            //上传商品推荐信息
            //查询所有商品推荐信息 
            List<Preference> list = wardRobeDao.GetPreferences(new BaseQuery());

            if (list != null && list.Count > 0)
            {
                String url = GlobalCache.UploadPerenceUrl;
                UploadPreference upload = new UploadPreference();
                upload.deviceID = GlobalCache.DeviceID;
                upload.storeID = GlobalCache.StoreID;
                upload.token = GlobalCache.loginUser.access_token;

                upload.data = list.ToArray();


                String data = jsonHelper.JsonSerializer<UploadPreference>(upload);
                //上传 
                String response = httpHelper.PostRequestJson(url, data);


                UploadPreferenceResponse cres = jsonHelper.JsonDeSerializer<UploadPreferenceResponse>(response);

                if (cres == null)
                    cres = new UploadPreferenceResponse() { isSuccess = false, message = "返回信息异常" };
                if (cres.isSuccess)
                {

                    foreach (Preference model in list)
                        //删除
                        wardRobeDao.DeleteById(model.id);
                    return 1;
                }
            }
            return -1;
        }
                 

        public void SaveShowToLocalBatch(List<WardRobe> list)
        {
       
            List<model.PreferenceShow> plist = new List<model.PreferenceShow>();
            foreach (WardRobe model in list)
            {
                //对于每一个商品先查询其相似商品再显示信息
                //远程下载搭配信息
                String url = GlobalCache.RankingUrl + "?token=" + GlobalCache.loginUser.access_token + "&storeid=" + model.Loaction + "&top=10&rfid=" + model.RFID;
                String response = httpHelper.GetRequestJson(url);

                RankingResponse cres = jsonHelper.JsonDeSerializer<RankingResponse>(response);
                if (cres == null)
                    cres = new RankingResponse() { isSuccess = false, message = "return data Exception" };

                if (cres.isSuccess)
                {
                    foreach (RankingVo vo in cres.GetData())
                    {
                        if(!String.IsNullOrEmpty(vo.rfid1))
                            AddItem(ref plist, model.Loaction, vo.rfid1);
                        if (!String.IsNullOrEmpty(vo.rfid2))
                            AddItem(ref plist, model.Loaction, vo.rfid2);
                        if (!String.IsNullOrEmpty(vo.rfid3))
                            AddItem(ref plist, model.Loaction, vo.rfid3);
                        if (!String.IsNullOrEmpty(vo.rfid4))
                            AddItem(ref plist, model.Loaction, vo.rfid4);
                        if (!String.IsNullOrEmpty(vo.rfid5))
                            AddItem(ref plist, model.Loaction, vo.rfid5);
                    }
                }
                else
                {
                    AddItem(ref plist,model.Loaction,model.RFID);
                }

  
            }
            wardRobeDao.SavePreferenceShowBatch(plist);  
        }


        private void AddItem(ref List<PreferenceShow> plist,String location,String rfid)
        {
            //远程下载搭配信息
            String url = GlobalCache.PreferenceListUrl + "?token=" + GlobalCache.loginUser.access_token + "&location=" + location + "&rfid=" + rfid;
            String response = httpHelper.GetRequestJson(url);

            PreferenceResponse cres = jsonHelper.JsonDeSerializer<PreferenceResponse>(response);
            if (cres == null)
                cres = new PreferenceResponse() { isSuccess = false, message = "return data Exception" };
            if (cres.isSuccess)
            {
                Preference[] array = (Preference[])cres.GetData();
                if (array.Length > 0)
                {
                    PreferenceShow pre = new PreferenceShow();
                    pre.Count = array.Length;
                    pre.rfid = rfid;
                    pre.remark = array[0].remark;
                    pre.location = array[0].location;
                    //目前显示的是一个持有时间
                    pre.holdtime = array[0].holdtime;
                    Commodity com = fittingService.GetCommodityRemote(new FittingQuery() { RFID = rfid, Url = GlobalCache.CommodityUrl });

                    //下载图片
                    if (!com.image.StartsWith("/"))
                        com.image = "/" + com.image;
                    fittingService.DownloadImage(GlobalCache.BaseUrl + com.image);

                    pre.image = Path.Combine(GlobalCache.BaseImgPath, Path.GetFileName(com.image));
                    pre.id = com.id;
                    pre.type = com.type;

                    plist.Add(pre);
                }
            } 
        }


        public List<PreferenceShow> GetPreferenceShows(IQuery query)
        {
            return wardRobeDao.GetPreferenceShows(query);
        }
    }


    /// <summary>
    /// 衣柜数据操作Service
    /// </summary>
    public class DxtWardRobeServiceImpl : IWardRobeService
    {
        /// <summary>
        /// 保存到本地
        /// </summary>
        private IWardRobeDao wardRobeDao = new WardRobeSqliteDaoImpl();
        private IFittingService fittingService = new FittingServiceImpl();
        private static HttpHelper httpHelper = new HttpHelper();
        private static JsonHelper jsonHelper = new JsonHelper();
        /// <summary>
        /// 操作数据的Service
        /// </summary>
        public void SaveToLocalBatch(List<model.WardRobe> list)
        {
            wardRobeDao.SaveWardRoleBatch(list);
        }

        /// <summary>
        /// 上传数据到远程服务器
        /// </summary>
        public int UploadData()
        {
            //上传商品推荐信息
            //查询所有商品推荐信息 
            List<Preference> list = wardRobeDao.GetPreferences(new BaseQuery());

            if (list != null && list.Count > 0)
            {
                String url = GlobalCache.UploadPerenceUrl;
                UploadPreference upload = new UploadPreference();
                upload.deviceID = GlobalCache.DeviceID;
                upload.storeID = GlobalCache.StoreID;
                upload.token = GlobalCache.loginUser.access_token;

                upload.data = list.ToArray();


                String data = jsonHelper.JsonSerializer<UploadPreference>(upload);
                //上传 
                String response = httpHelper.PostRequestJson(url, data);


                UploadPreferenceResponse cres = jsonHelper.JsonDeSerializer<UploadPreferenceResponse>(response);

                if (cres == null)
                    cres = new UploadPreferenceResponse() { isSuccess = false, message = "返回信息异常" };
                if (cres.isSuccess)
                {

                    foreach (Preference model in list)
                        //删除
                        wardRobeDao.DeleteById(model.id);
                    return 1;
                }
            }
            return -1;
        }


        public void SaveShowToLocalBatch(List<WardRobe> list)
        { 
            FileStream fs = null;
            string filePath = ConfigurationManager.AppSettings["savetxt"];

            if (!File.Exists(filePath))
                File.Create(filePath);
            //将待写的入数据从字符串转换为字节数组  
            Encoding encoder = Encoding.UTF8;
            String data = string.Empty;

            foreach (WardRobe wr in list)
                data += (wr.RFID + "|" + wr.ReadTime + "|" + wr.ReaderIdentity +"|"+wr.Ant +";");

            if (data.Length > 0)
            {
                data = data.Substring(0, data.Length - 1);
                byte[] bytes = encoder.GetBytes(data);
                try
                {
                    fs = File.OpenWrite(filePath);
                    //设定书写的开始位置为文件的末尾  
                    fs.Position = fs.Length;
                    //将待写入内容追加到文件末尾  
                    fs.Write(bytes, 0, bytes.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("文件打开失败{0}", ex.ToString());
                }
                finally
                {
                    fs.Close();
                }
            }
        }

        private void Write()
        {
            String path = ConfigurationManager.AppSettings["savetxt"];
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入\
          
            sw.Write("");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();

        }


        private void AddItem(ref List<PreferenceShow> plist, String location, String rfid)
        {
            //远程下载搭配信息
            String url = GlobalCache.PreferenceListUrl + "?token=" + GlobalCache.loginUser.access_token + "&location=" + location + "&rfid=" + rfid;
            String response = httpHelper.GetRequestJson(url);

            PreferenceResponse cres = jsonHelper.JsonDeSerializer<PreferenceResponse>(response);
            if (cres == null)
                cres = new PreferenceResponse() { isSuccess = false, message = "return data Exception" };
            if (cres.isSuccess)
            {
                Preference[] array = (Preference[])cres.GetData();
                if (array.Length > 0)
                {
                    PreferenceShow pre = new PreferenceShow();
                    pre.Count = array.Length;
                    pre.rfid = rfid;
                    pre.remark = array[0].remark;
                    pre.location = array[0].location;
                    //目前显示的是一个持有时间
                    pre.holdtime = array[0].holdtime;
                    Commodity com = fittingService.GetCommodityRemote(new FittingQuery() { RFID = rfid, Url = GlobalCache.CommodityUrl });

                    //下载图片
                    if (!com.image.StartsWith("/"))
                        com.image = "/" + com.image;
                    fittingService.DownloadImage(GlobalCache.BaseUrl + com.image);

                    pre.image = Path.Combine(GlobalCache.BaseImgPath, Path.GetFileName(com.image));
                    pre.id = com.id;
                    pre.type = com.type;

                    plist.Add(pre);
                }
            }
        }


        public List<PreferenceShow> GetPreferenceShows(IQuery query)
        {
            return wardRobeDao.GetPreferenceShows(query);
        }
    }
}
